import React, { Component } from 'react'

export default class Count extends Component {
    state = { count: 0 }

    add = () => {
        const { count } = this.state
        const { value } = this.selectNum
        // *1强制类型转换
        this.setState({count: count + value * 1})
    }

    minus = () => {
        const { count } = this.state
        const { value } = this.selectNum
        this.setState({count: count - value * 1})
    }

    addIfOdd = () => {
        const { count } = this.state
        const { value } = this.selectNum
        if (count % 2 !== 0) this.setState({count: count + value * 1})
    }

    addAsync = () => {
        const { count } = this.state
        const { value } = this.selectNum
        setTimeout(() => {
            this.setState({count: count + value * 1});
        }, 1000)
    }

    render() {
        return (
            <div>
                <h1>当前求和为: {this.state.count}</h1>
                <select ref={c => this.selectNum = c} name="" id="">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.add}>+</button>&nbsp;
                <button onClick={this.minus}>-</button>&nbsp;
                <button onClick={this.addIfOdd}>当前求和为奇数时, +</button>&nbsp;
                <button onClick={this.addAsync}>异步, +</button>&nbsp;
            </div>
        )
    }
}
